import { login, logout, ticketLogin } from '@/api/user'
import { getToken, setToken, removeToken, getRoles, setRoles, removeRoles, getUserID, setUserID, removeUserID, getUserName, setUserName, removeUserName } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  userID: ''
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_ID: (state, userID) => {
    state.userID = userID
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        if (!data) {
          reject('验证失败，请重新登录.')
        }
        if (data.relo) {
          data.relo = data.relo.toLocaleLowerCase()
        }
        const { relo, token, userName, userID } = data
        var roles = []
        roles.push(relo)

        if (!roles || roles.length <= 0) {
          reject('没有角色权限!')
        }

        setRoles(roles)
        setUserID(userID)
        setUserName(userName)
        setToken(token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  ticketLogin({ commit }, payload) {
    const { ticket, url } = payload
    return new Promise((resolve, reject) => {
      ticketLogin(ticket, url).then(response => {
        const { data } = response
        if (!data) {
          reject('验证失败，请重新登录.')
        }
        // if (data.relo) {
        //   // data.relo = data.relo.toLocaleLowerCase()
        //   data.relo = 'admin'
        // }
        const { relo, token, userName, userID } = data
        var roles = ['admin']
        roles.push(relo)
        if (!roles || roles.length <= 0) {
          reject('没有角色权限!')
        }

        setRoles(roles)
        setUserID(userID)
        setUserName(userName)
        setToken(token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      const data = {
        token: getToken(),
        roles: getRoles(),
        userID: getUserID(),
        userName: getUserName()
      }
      if (!data.token) {
        reject('验证失败，请重新登录.')
      }

      if (!data.roles || data.roles.length <= 0) {
        reject('没有角色权限!')
      }

      if (!data.userID) {
        reject('没有userID!')
      }
      commit('SET_TOKEN', data.token)
      commit('SET_ROLES', data.roles)
      commit('SET_NAME', data.userName)
      commit('SET_ID', data.userID)

      resolve(data)
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_NAME', '')
        commit('SET_ID', '')
        commit('SET_ROLES', [])
        removeToken()
        removeRoles()
        removeUserID()
        removeUserName()
        resetRouter()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // Dynamically modify permissions this.$store.dispatch('user/changeRoles')动态更新路由测试
  changeRoles({ dispatch, rootGetters }) {
    return new Promise(async resolve => {
      // resetRouter()
      const userID = rootGetters.userID
      const pageRoutes = rootGetters.permission_routes
      const addRoutes = {
        id: 3235,
        meta: {
          title: '新项目-角色管理2'
        },
        moduleName: '新项目-角色管理2',
        name: 'Role1',
        path: 'Role1',
        component: () => import('@/views/guide/index'),
        type: 2,
        url: '/system/Role'
      }
      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/getgenerateRoutes', { userID, accessRoutes: pageRoutes }, { root: true })
      accessRoutes[accessRoutes.length - 2].children.push(addRoutes)
      console.log(accessRoutes)
      // dynamically add accessible routes
      router.addRoutes(accessRoutes)
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
